/**
 * @description 读取resoucres/json下的.json文件
 */
import Singleton from "./Singleton";
import { _decorator, AssetManager, assetManager} from 'cc';
const {ccclass, property} = _decorator;

export default class GameConfig extends Singleton {
	public tables: any = {};

	public async loadTable(loadProgress?:Function,bundle:string="resources"):Promise<void>{
		return new Promise<void>(resolve=>{
			assetManager.loadBundle(bundle,(error,bundle:AssetManager.Bundle)=>{
				if (error) {
					console.error("json bundle加载错误!");

					return;
				}

				const progress = (finish: number, total: number, item):void => {
					if (loadProgress) {
						loadProgress(finish, total, item);
					}
				};

				const onload = (err, assets):void => {
					if (err) {
						console.log('加载json文件失败');

						return;
					}

					console.log('初始化json文件成功:' + assets.length);
					let asset: { name: string | number; json: any; };

					for (let i = 0; i < assets.length; i++) {
						asset = assets[i];
						this.tables[asset.name] = asset.json;
					}

					resolve();
				};

				bundle.loadDir("config", progress, onload)
				// loader.loadResDir('json', progress, onload);
			})
		})
	}

	public cleanTable(name:string):void{
		if(name!=null && name!=""){
			this.tables[name] = null;
		}else{
			this.tables = null;
		}
	}

	public getTable(name:string):any{
		return this.tables[name];
	}

	public getTableValueByKey(name:string,key:string,value:any):any{
		const table = this.getTable(name);

		for (const k in table) {
			if (Object.prototype.hasOwnProperty.call(table, k)) {
				const t = table[k];

				if (value == t[key]) {
					return t;
				}
			}
		}
	}

	/**
	 * 不是所有json表都适用..
	 * let test = TableManager.Instance().getTableArray(activity_bank);
	 * for (const key in test) {
     *      if (Object.prototype.hasOwnProperty.call(test, key)) {
     *          const element = test[key];
     *          console.log("222element:" + element)
     *      }
     *  }
	 * console.log("test[1]:" + JSON.stringify(test[1]))
     * console.log("test.length:" + test.length + "  " + Object.keys(test))
	 * @param t 
	 * @returns 
	 */
	public getTableArray<T>(t:{new():T}): Array<T>{
		return this.tables[t.name] as Array<T>;
	}

	/**
	 * 不是所有json表都适用..
	 * @param t 
	 * @param id 
	 * @returns 
	 */
	public getTableValueByArrayID<T>(t:{new():T},id:number):T{
		const table = this.getTableArray(t);

		if (table[id]) {
			return table[id];
		}

		for (const key in table) {
			if (Object.prototype.hasOwnProperty.call(table, key)) {
				const t = table[key];

				if (t['id'] == id) {
					return t;
				}
			}
		}
	}
}